﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.Query;

namespace NBusiness.Data.Providers.SqlServer.Query
{
    public class SqlDelete : SqlParameters, IDelete
    {
        #region IDelete Members

        private ITable _table;
        private IExpression _expression;

        public IDelete From(ITable table)
        {
            _table = table;
            return this;
        }

        public void Where(IExpression expression)
        {
            _expression = expression;
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            return ToSql(new SqlQueryContext(AliasAssignmentStyle.None));
        }

        public string ToSql(IQueryContext context)
        {
            if (_table == null)
                throw new InvalidOperationException("You must specify a table to delete from");

            StringBuilder builder = new StringBuilder("DELETE FROM ");
            builder.Append(_table.ToSql(context));
            
            if (_expression != null)
            {
                builder.Append(" WHERE ");
                builder.Append(_expression.ToSql(context));
            }

            return builder.ToString();
        }

        #endregion
    }
}
